package com.cyx.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过ServletContext 共享数据
        ServletContext servletContext = this.getServletContext();
        String userName = (String) servletContext.getAttribute("userName");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("<html><head><title>标题</title></head>");
        writer.println("<body>");
        writer.println("<p>userName="+userName+"</p>");
        writer.println("<p>getServletContextName: "+servletContext.getServletContextName()+"</p>");
        writer.println("<p>getContextPath: "+servletContext.getContextPath()+"</p>");
        writer.println("<p>req.getContextPath: "+req.getContextPath()+"</p>");
        writer.println("<p>getServerInfo: "+servletContext.getServerInfo()+"</p>");
        writer.println("<p>getVirtualServerName: "+servletContext.getVirtualServerName()+"</p>");
        writer.println("-------------------- 获取初始化参数 --------------------------");
        writer.println("<p>db-url:"+servletContext.getInitParameter("db-url")+"</p>");
        writer.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
